package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.customer.mapper.AccountMapper;
import com.jzo2o.customer.model.domain.Account;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IAccountService;
import com.jzo2o.mvc.utils.UserContext;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 银行账户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-02
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    /**
     * 新增修改账户，二合一接口
     * @param dto
     */
    @Override
    public void addOrUpdateBankAccount(BankAccountUpsertReqDTO dto,Integer type) {
        //无论是新增还是修改，都必须校验
//        if(!matches(dto.getName(),"^[\\u4e00-\\u9fa5]{2,10}$")){
//            throw new CommonException("户名只能为2-10个汉字");
//        }
//        if(!matches(dto.getBranch(),"^[\\u4e00-\\u9fa5]{4,50}$")){
//            throw new ForbiddenOperationException("网点名称只能为4-50个汉字");
//        }
//        if(!matches(dto.getAccount(),"^\\d{16}|\\d{17}|\\d{19}")){
//            throw new ForbiddenOperationException("银行账户储蓄卡位数只能为16位，17位，18位");
//        }
        //查询当前账户是否存在
        Integer count = this.lambdaQuery()
                .eq(Account::getCreateBy, UserContext.currentUserId())
                .count();
        if (count == 0){
            //是空就做新增
            Account account = BeanUtils.copyBean(dto, Account.class);
            boolean save = this.save(account);
            if (!save){
                throw  new DBException("保存失败");
            }
        }else {
            //不是空，就做修改操作
            Account account = BeanUtils.copyBean(dto, Account.class);
            boolean remove = this.lambdaUpdate()
                    .eq(Account::getCreateBy, UserContext.currentUserId())
                    .remove();
            //新增数据
            account.setType(Long.valueOf(type));
            boolean result = this.save(account);
            if (!result){
                throw new DBException("修改账户失败");
            }
        }
    }


    /**
     * 获取账户信息
     * @param id
     * @return
     */
    @Override
    public BankAccountResDTO getByIdAccount(Long id) {
        Account account = this.lambdaQuery()
                .eq(Account::getCreateBy, UserContext.currentUserId())
                .one();
        if (ObjectUtils.isEmpty(account)){
            return null;
        }
        BankAccountResDTO resDTO = BeanUtils.copyBean(account, BankAccountResDTO.class);
        return resDTO;
    }


}
